import { createSlice, createAsyncThunk, type PayloadAction } from '@reduxjs/toolkit'
import type { IUsers, IUsersWrite } from '../../types/users'
import http from '../../api/http'

//初始化值
const initialState: Array<IUsers> = []


//处理一个异步请求
const fetchUsers = createAsyncThunk(
    "users/fetch",
    async () => {
        // const response = await fetch(`http://localhost:5035/api/Users`);
        // const users = await response.json();
        // return users;

        return await http.get<Array<IUsers>>('Users');

    }
)

//添加用户的异步方法
const insertUser = createAsyncThunk(
    'user/insert',
    async (user:IUsersWrite)=>{
        return await http.post('Users',user)
    }
)


const userSlice = createSlice({
    name: 'cart',
    //state 初始化值
    initialState,
    reducers: {
        //action 
        //有参数的方法
        addUser(state, action: PayloadAction<IUsersWrite>) {

        },
    },
    //在这里 监听异步结果
    extraReducers:(builder)=>{
        builder.addCase(fetchUsers.fulfilled,(state,action)=>{
            //action.payload
            console.log('action.payload: ', action.payload);
            //action.payload.
            state.length=0
            state.push(...action.payload.data)
        }),

        //监听添加
        builder.addCase(insertUser.fulfilled,(state,action)=>{
            //action.payload
            console.log('action.payload: ', action.payload);
        })
    }
})


// 解构  action 
const { addUser } = userSlice.actions

//统一导出
export {addUser,fetchUsers,insertUser}
export default userSlice.reducer
